#!/usr/bin/python
#-*- coding: utf-8 -*-
import platform
import sys
import os
import time
import thread
from subprocess import Popen, PIPE

# 传入ip地址，调用 cmd ping, 返回 Popen 对象
# 指定ping的stdout通过管道写入设定的buffer中
def invoke_ping(addr):
    # windows 的参数和linux下不同
    cmd = ['ping', '-c', '1', addr]
    ret = 0
    try:
        ret = Popen(cmd, bufsize=1024, stdout=PIPE)
    except ValueError:
        print 'error occur in invoke_ping: ' + addr
    return ret

# 简单地通过 ping 回显信息检查是否在线
def check_online(popen_obj):
    echo = popen_obj.communicate()[0].split('\n')
    if len(echo) >= 3:
        # print echo[1]
        ttl_pos = echo[1].find('ttl')
        if ttl_pos != -1:
            ms_pos = echo[1].find('ms')
            i = ms_pos - 2
            while i > 0 and echo[1][i:i + 1].isdigit() == True or echo[1][i:i + 1] == ".":
                i -= 1
            ti = float(echo[1][i+1:ms_pos])

            t = ttl_pos + 4
            while echo[1][t:t + 1].isdigit() == True:
                t += 1
            ttl = int(echo[1][ttl_pos+4 : t])
            return (ti, ttl)
    return tuple()

def ping_scan(dst):
    oks = []
    scq = {}
    net_addr = dst.split('.')
    # ip_list = [73, 74, 75, 83, 84, 85, 93, 94, 95, 76, 86, 96 ]
    ip_list = [73, 74, 75, 83, 84, 85, 93, 94, 95, 76, 86, 96 ]

    for i in ip_list:
        #[10.10.6.73,10.10.6.74,10.10.6.75,...]
        net_addr[3] = str(i)
        tmp = invoke_ping( '.'.join(net_addr))
        if type(tmp) != int:
            scq[i] = tmp

    while len(scq) != 0:
        to_be_removed = []
        for k, v in scq.items():
            # k: ip last num
            if v.wait() != None:
                ret = check_online(v)
                if len(ret) > 0:
                    #ret = (0.185, 64)
                    net_addr[3] = str(k)
                    # net_addr ['10', '10', '6', '1']
                    oks.append( ( k, ret) )
                to_be_removed.append( k )
        for i in to_be_removed:
            scq.pop(i)
    #[(96, (0.19900000000000001, 64)), (73, (0.186, 64)), (74, (0.22600000000000001, 64)),...
    return oks

if __name__ == '__main__':
    start_time = time.clock()
    dst_net = '10.10.6.173'
    online_list = ping_scan(dst_net)
    online_list.sort()
    print len(online_list)
    #oneline_line    [(96, (0.19900000000000001, 64)), (73, (0.186, 64)), (74, (0.22600000000000001, 64)),...

    # prefix = '.'.join( dst_net.split('.')[0:3] )
    # prefix 10.10.6
    # for i in online_list:
    #     fmt = '%s time=%.3fms ttl=%d'
    #     print fmt % ( prefix+'.'+str(i[0]), float(i[1][0]), i[1][1] )
    # print '%d hosts in total' % len(online_list)
    # print 'process time: %lfs' % (time.clock() - start_time)